<template>
  <div>
    <div>
      <LittleTitle :title="`新增用户下的门锁：`"></LittleTitle>
      <div class="add-lock">
        <div class="add-lock-item">
          用户名：<a-input class="input" v-model="add.name"></a-input>
        </div>
        <div class="add-lock-item">
          设备ID：<a-input class="input" v-model="add.identityId"></a-input>
        </div>
        <div class="add-lock-item">
          地理位置：<a-input class="input" v-model="add.location"></a-input>
        </div>
        <a-button type="primary" @click="addLock">添加门锁</a-button>
      </div>
    </div>

    <div>
      <!-- <LittleTitle
        :title="`点击查询用户下所有门锁`"
        @click.native="userLockShow = !userLockShow"
      ></LittleTitle> -->

      <div class="lil-title" @click="userLockShow = !userLockShow">点击查询用户下的所有门锁</div>
      <div v-if="userLockShow" class="user-lock">
        <div style="margin-bottom: 20px">
          用户名：<a-input class="input" v-model="userLockName"></a-input>
          <a-button type="primary" @click="lockByUser">查询</a-button>
        </div>

        <!-- 门锁数据 -->
        <div>
          <a-table bordered :data-source="userLock" :columns="columns">
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm
                v-if="userLock.length"
                title="确认注销该用户下的这把门锁吗？"
                okText="确定"
                cancelText="取消"
                @confirm="delLock(text, record)"
              >
                <!-- <a href="javascript:;" style="color: red">注销</a> -->
                <button class="operate1">注销</button>
              </a-popconfirm>
              <!-- <span style="color: lightgray"> | </span> -->
              <!-- <a @click="showModal(text, record)">绑定卡号</a> -->
              <button class="operate2" @click="showModal(text, record)">绑定卡号</button>
            </template>
          </a-table>
          <!-- 绑定卡号弹出框 -->
          <a-modal
            :bodyStyle="bodyStyle"
            v-model="lockCardModal"
            title="设备与卡号绑定"
            ok-text="确认"
            cancel-text="取消"
            @ok="lockAddCardnumber"
          >
            <div class="lock-card">
              <div class="lock-card-item">
                设备ID：{{ lockAddCard.identityId }}
              </div>
              <div class="lock-card-item">
                卡号：<a-input
                  class="input"
                  v-model="lockAddCard.cardNumber"
                ></a-input>
              </div>
              <div class="lock-card-item">
                超管密码：<a-input
                  class="input"
                  v-model="lockAddCard.rootPassWord"
                  type="password"
                ></a-input>
              </div>
            </div>
          </a-modal>
        </div>
      </div>
    </div>

    <div>
      <!-- <LittleTitle
        :title="`点击查看已注册的所有门锁`"
        @click.native="getAllLock"
      ></LittleTitle> -->

      <div class="lil-title" @click="getAllLock">点击查看已注册的所有门锁</div>
      <!-- 所有门锁数据 -->
      <div v-if="allLock.show" class="user-lock">
        <a-table :data-source="allLock.data" :columns="allLock.columns">
          <div
            slot="filterDropdown"
            slot-scope="{
              setSelectedKeys,
              selectedKeys,
              confirm,
              clearFilters,
              column,
            }"
            style="padding: 8px"
          >
            <a-input
              v-ant-ref="(c) => (searchInput = c)"
              :placeholder="`Search ${column.dataIndex}`"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block;"
              @change="
                (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
              "
              @pressEnter="
                () => handleSearch(selectedKeys, confirm, column.dataIndex)
              "
            />
            <a-button
              type="primary"
              icon="search"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="
                () => handleSearch(selectedKeys, confirm, column.dataIndex)
              "
            >
              Search
            </a-button>
            <a-button
              size="small"
              style="width: 90px"
              @click="() => handleReset(clearFilters)"
            >
              Reset
            </a-button>
          </div>
          <a-icon
            slot="filterIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <template
            slot="customRender"
            slot-scope="text, record, index, column"
          >
            <span v-if="allLock.searchText && searchedColumn === column.dataIndex">
              <template
                v-for="(fragment, i) in text
                  .toString()
                  .split(
                    new RegExp(`(?<=${allLock.searchText})|(?=${allLock.searchText})`, 'i')
                  )"
              >
                <mark
                  v-if="fragment.toLowerCase() === allLock.searchText.toLowerCase()"
                  :key="i"
                  class="highlight"
                  >{{ fragment }}</mark
                >
                <template v-else>{{ fragment }}</template>
              </template>
            </span>
            <template v-else>
              {{ text }}
            </template>
          </template>

          <template slot="state" slot-scope="text, record, index, column">
            <div>
              {{ text.state ? "开启中" : "关闭中" }}
            </div>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {},
  data() {
    return {
      add: {
        name: "",
        location: "",
        identityId: "",
      },
      userLockName: "xhc",
      userLock: [],
      userLockShow: false,
      columns: [
        {
          title: "设备ID",
          dataIndex: "name",
          key: "name",
          width: "20%",
        },
        {
          title: "设备ID",
          dataIndex: "identityId",
          key: "identityId",
          width: "20%",
        },
        {
          title: "位置",
          dataIndex: "location",
          key: "location",
        },
        {
          title: "操作",
          scopedSlots: { customRender: "operation" },
          width: "20%",
        },
      ],
      lockCardModal: false,
      bodyStyle: {
        height: "180px",
      },
      lockAddCard: {
        cardNumber: "",
        identityId: "",
        rootPassWord: "",
      },
      allLock: {
        show: false,
        data: [],
        searchText: '',
      searchInput: null,
      searchedColumn: '',
        columns: [
          {
            title: "设备ID",
            dataIndex: "identityId",
            key: "identityId",
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender",
            },
            onFilter: (value, record) =>
              record.identityId
                .toString()
                .toLowerCase()
                .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
              if (visible) {
                setTimeout(() => {
                  this.searchInput.focus();
                }, 0);
              }
            },
          },
          {
            title: "所属用户",
            dataIndex: "name",
            key: "name",
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender",
            },
            onFilter: (value, record) =>
              record.name
                .toString()
                .toLowerCase()
                .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
              if (visible) {
                setTimeout(() => {
                  this.searchInput.focus();
                });
              }
            },
          },
          {
            title: "位置",
            dataIndex: "location",
            key: "location",
            scopedSlots: {
              filterDropdown: "filterDropdown",
              filterIcon: "filterIcon",
              customRender: "customRender",
            },
            onFilter: (value, record) =>
              record.location
                .toString()
                .toLowerCase()
                .includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
              if (visible) {
                setTimeout(() => {
                  this.searchInput.focus();
                });
              }
            },
          },
          {
            title: "状态",
            scopedSlots: {
              customRender: "state",
            },
          },
          {
            title: "最后一次修改时间",
            dataIndex: "time",
            key: "time",
          },
        ],
      },
    };
  },
  methods: {
    async addLock() {
      if (!this.add.name) {
        this.$message.warning("请填写用户名！");
      } else if (!this.add.identityId) {
        // TODO:正则表达式判断是否为6位数字
        this.$message.warning("请填写设备ID！");
      } else if (!this.add.location) {
        this.$message.warning("请填写设备对应的地理位置！");
      } else {
        const res = await this.$_api.addLock(this.add);
        const msg = res.data.message;
        console.log(msg);
        // TODO：需要完善
        switch (msg) {
          case "增加成功":
            this.$message.success(
              `已为用户${this.add.name}添加门锁设备，设备ID为${this.add.identityId}！`
            );
            for (let i in this.add) {
              this.add[i] = "";
            }
            break;
        }
      }
    },
    async lockByUser() {
      const data = {
        username: this.userLockName,
      };
      const res = await this.$_api.getUserLock(data);
      this.userLock = res.data.data.list;
    },
    async delLock(t, r) {
      const data = {
        identityId: r.identityId,
      };
      const res = await this.$_api.delLock(data);
      // console.log(res);
      if (res.data.message == "删除成功") {
        this.$message.success(`设备${r.identityId}注销成功！`);
        this.lockByUser();
      } else {
        this.$message.success(`ERROR`);
      }
    },
    async lockAddCardnumber() {
      const res = await this.$_api.lockAddCard(this.lockAddCard);
      const msg = res.data.data.message;
      console.log(msg);
      switch (msg) {
        case "卡号不存在":
          this.$message.warning("卡号不存在，请确认卡号！");
          break;
        case "超管密码不正确":
          this.$message.warning("超管密码不正确，请重新输入密码！");
          this.lockAddCard.rootPassWord = "";
          break;
        case "已存在卡号和锁对应记录":
          this.$message.warning(msg);
          break;
        case "添加成功":
          this.$message.success(
            `设备${this.lockAddCard.identityId}与卡号${this.lockAddCard.cardNumber}绑定成功！`
          );
      }
    },
    // 门锁与卡号绑定面板
    showModal(t, r) {
      this.lockCardModal = true;
      console.log(t, r);
      this.lockAddCard.identityId = r.identityId;
    },

    async getAllLock() {
      this.allLock.show = !this.allLock.show;
      if (this.allLock.show) {
        const res = await this.$_api.getAllLock();
        this.allLock.data = res.data.data.list;
      }
    },
    // 所有门锁数据有关
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.allLock.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },

    handleReset(clearFilters) {
      clearFilters();
      this.allLock.searchText = "";
    },
  },
};
</script>
<style lang="less" scoped>
.input {
  width: 200px;
  margin-right: 10px;
}
.add-lock {
  margin-bottom: 80px;
}
.lil-title{
  background: #e3f0ff;
  padding: 10px;
  border-left: 8px solid #1890ff;
  border-radius: 5px;
  font-size: 16px;
  margin: 40px 0;
  transition: background 0.5s;
  &:hover{
    cursor: pointer;
    background: #cce5fd;
  }
}
.add-lock-item {
  display: inline-block;
}
@media screen and (max-width: 800px) {
  .add-lock-item {
    display: block;
    margin-bottom: 20px;
  }
}
@keyframes slide-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.user-lock {
  animation: slide-in 0.5s;
}
/* .all-lock {
  cursor: pointer;
} */
.lock-card-item {
  margin-bottom: 20px;
}
.operate1{  
  border: none;
  color: white;
  background: rgb(255, 59, 59);
  border-radius: 5px;
  outline: none;
  padding: 4px 10px;
  margin-right: 10px;
  transition: background 0.5s;
  &:hover{
    cursor: pointer;
    background: rgb(240, 0, 0);
  }
}

.operate2{
  border: none;
  color: white;
  background: #4396f5;
  border-radius: 5px;
  outline: none;
  padding: 4px 10px;

  transition: background 0.5s;
  &:hover{
    cursor: pointer;
    background: #0066da;
  }
}
</style>
